package com.liry.mybatis.datascope.model;

import java.util.Iterator;
import java.util.Map;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.Configuration;

/**
 * 自定义boundsql
 *
 * @author ALI
 * @since 2022/9/13
 */
public class DataScopeSqlSource implements SqlSource {
    private final MetaObject metaObject;
    private final BoundSql boundSql;

    public DataScopeSqlSource(Configuration configuration, String sql, BoundSql boundSql) {
        this.metaObject = SystemMetaObject.forObject(boundSql);
        this.boundSql = new BoundSql(configuration, sql, boundSql.getParameterMappings(),
                                     boundSql.getParameterObject());
        Map<String, Object> objectMap = getParameters();
        if (null != objectMap) {
            Iterator<Map.Entry<String, Object>> entryIterator = objectMap.entrySet().iterator();

            while (entryIterator.hasNext()) {
                Map.Entry<String, Object> entry = entryIterator.next();
                this.boundSql.setAdditionalParameter(entry.getKey(), entry.getValue());
            }
        }
    }

    public BoundSql getBoundSql(Object var1) {
        return this.boundSql;
    }

    public Map<String, Object> getParameters() {
        return (Map<String, Object>) this.metaObject.getValue("additionalParameters");
    }

}
